<template>
  <div class="container">
    <!-- 查看,编辑 -->
    <edit :visible="editVisible" :type="handelType" :data="list" :unitData="organizes" :earlyType="earlyTypeArr"
      :earlyLevel="classTypeArr" @cancel="cancel"></edit>
    <div class="tableColumns">
      <!--数据统计 数据筛选 信息列表-->
      <div class="right-columns">
        <!--数据统计-->
        <div class="table-stat" v-loading="earlyTrendLoading">
          <span style="display: block;color: #353A42;font-size: 16px;font-weight: bold;padding-left: 10px;">
            <span>{{ spanText }}</span>
          </span>
          <el-form label-position="right">
            <el-row :gutter="24">
              <el-col :span="7">
                <el-form-item label="时间" label-width="100px">
                  <el-date-picker v-model="statForm.time" type="daterange" range-separator="至" start-placeholder="开始时间"
                    end-placeholder="结束时间" :popper-options="popOptions" />
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="责任单位" label-width="100px">
                  <el-select v-model="statForm.responsibleUnit" placeholder="请选择" :clearable="true" filterable>
                    <el-option v-for="item in organizes" :key="item.id" :label="item.departName"
                      :value="item.departName">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="7">
                <el-form-item label="处理状态" label-width="100px">
                  <el-select v-model="statForm.isState" placeholder="请选择" :clearable="true">
                    <el-option v-for="item in statusTypeArr" :key="item.tshsId" :label="item.tshsStat"
                      :value="item.tshsId">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3" style="text-align: right">
                <el-button @click="resetStatForm">清空</el-button>
                <el-button type="primary" @click="getEarlyTrend">查询</el-button>
              </el-col>
            </el-row>
          </el-form>
          <div style="width: 100%;height: 100%;">
            <div class="c1" style="float: left; height: 100%; width: 50%">
              <span>
                <strong style="font-size: 25px">
                  {{ spanText4 }}
                </strong>
              </span>
              <div id="picture1" style="width: 100%;height: 80%"></div>
            </div>
            <div class="c2" style="float: left; width:45%">
              <div style="height: 38px">
                <div style="float: left;">
                  <span>
                    <strong style="font-size: 25px">
                      {{ spanText5 }}
                    </strong>
                  </span>
                </div>
              </div>
              <div id="picture2" style="width: 100%;height: 390px"></div>
            </div>
          </div>
        </div>
        <div v-loading="earlyLoading">
          <!-- 数据筛选-->
          <div class="table-select">
            <span style="display: block;color: #353A42;font-size: 16px;font-weight: bold;padding-left: 10px;">
              <span>{{ spanText2 }}</span>
            </span>
            <el-form label-position="right">
              <el-row :gutter="24">
                <el-col :span="7">
                  <el-form-item label="隐患编号" label-width="100px">
                    <el-input v-model="retrievedForm.tshlId" placeholder="请输入隐患编号" :clearable="true" />
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="隐患分类" label-width="100px">
                    <el-select filterable v-model="retrievedForm.tshlClassify" placeholder="请选择" :clearable="true">
                      <el-option v-for="item in earlyTypeArr" :key="item.tsharId" :label="item.tsharClassify"
                        :value="item.tsharClassify">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="隐患等级" label-width="100px">
                    <el-select v-model="retrievedForm.tshlGrade" placeholder="请选择" :clearable="true">
                      <el-option v-for="item in classTypeArr" :key="item.id" :label="item.value" :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24">
                <el-col :span="7">
                  <el-form-item label="责任单位" label-width="100px">
                    <el-select v-model="retrievedForm.tshlUnit" placeholder="请选择" :clearable="true" filterable>
                      <el-option v-for="item in organizes" :key="item.id" :label="item.departName"
                        :value="item.departName">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="7">
                  <el-form-item label="处理状态" label-width="100px">
                    <el-select v-model="retrievedForm.tshlStat" placeholder="请选择" :clearable="true">
                      <el-option v-for="item in statusTypeArr" :key="item.tshsId" :label="item.tshsStat"
                        :value="item.tshsId">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="7">
                  <el-form-item label="创建时间" label-width="100px">
                    <el-date-picker v-model="retrievedForm.time" type="datetimerange" range-separator="至"
                      start-placeholder="开始时间" end-placeholder="结束时间" :clearable="true"
                      style="width: 310px !important;" />
                  </el-form-item>
                </el-col>
                <el-col :span="3" style="text-align: right">
                  <el-button @click="searchReset">清空</el-button>
                  <el-button type="primary" @click="getList">查询</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <!--信息列表-->
          <div class="table-commons">
            <span class="title-span">
              <span style="border-left: 2px solid #fff;    padding-left: 0;">{{ spanText3 }}</span>
              <div style="display: flex;align-items: center">
                <el-button type="primary" :disabled="nodeRowData.children.length !== 0" @click="addRouter(1, {})"
                  style="margin-left: 10px">新增</el-button>
              </div>
            </span>
            <!--表格内容-->
            <table-common :loading="loading" :columns="exampleColumns" :pagination="pager" :table-data="tableData"
              @size-change="sizeChange" @current-change="currentChange" :height="'450px'" @sort-change="sortChange">
              <template #tshlStat="{ row }">
                <!-- 自定义操作栏示例  -->
                <!--<div class="statusRow" :style="{color:getColor(row.isState),background:getBackColor(row.isState),borderColor:getColor(row.isState)}">-->
                <div :style="{ color: row.tshlStat == '0' ? 'red' : '#535862' }">
                  {{ filterStatus(row.tshlStat) }}
                </div>
              </template>

              <template #earlyLevel="{ row }">
                <!-- 自定义操作栏示例  -->
                <div>
                  {{ setLevelDesc(row.earlyLevel) }}
                </div>
              </template>

              <template #responsibleUnit="{ row }">
                <!-- 自定义操作栏示例  -->
                <div>
                  {{ setUnitName(row.responsibleUnit) }}
                </div>
              </template>

              <template #action="{ row }">
                <!-- 自定义操作栏示例  -->
                <el-button class="link-btn" link type="primary" @click="handleEarly(row, false)">查看
                </el-button>
                <el-button v-if="row.tshlStat == 1" class="link-btn" link type="primary" @click="addRouter(1, row)">编辑
                </el-button>
                <el-button v-if="row.tshlStat == 2 || row.tshlStat == 0" class="link-btn" link type="primary"
                  @click="handleEarly(row, true)">处理
                </el-button>
                <el-button v-if="row.tshlStat == 3" class="link-btn" link type="primary"
                  @click="handleEarly(row, true)">验收
                </el-button>
                <el-button v-if="row.tshlStat == 5" class="link-btn" link type="primary"
                  @click="handleEarly(row, true)">解除
                </el-button>
                <el-popconfirm v-if="row.tshlStat == 1" title="是否删除?" confirmButtonText="确定" cancelButtonText="取消"
                  @confirm="() => deleteEarly(row)">
                  <template #reference>
                    <el-button v-if="row.tshlStat == 1" class="link-btns" link type="primary">删除
                    </el-button>
                  </template>
                </el-popconfirm>
              </template>
            </table-common>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
/**
 * @Name: 引入文件内容
 * @Author: cdfy2
 * @Date: 2023/16/13  16:25:31
 */
import { Search } from '@element-plus/icons-vue'
import { ElTree, ElMessage } from 'element-plus'
import { exampleColumns } from './config/columns'
import TableCommon from '@/components/TableCommon/index.vue'
import edit from './edit.vue'
import { unitList } from '@/api/secure/recycleUnits'
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import { updateStatus } from '@/api/quality/schedule'
import { inventoryPageList, inventoryTrend, earlyTypeList, updateInventory, deleteInventory, getEarlyState } from '@/api/secure/inventory'
import { getResource } from '@/api/resource'
import router from '@/router'
import * as echarts from 'echarts';
import { findFile } from '../../../../api/secure/inventory'



/**
 * @Name: 界面参数-start
 * @Author: cdfy2
 * @Date: 2023/16/13  16:19:57
 * @param:
 */
//分页表格查询参数
const retrievedForm = ref({
  tshlId: '',
  tshlNumber: '',
  tshlName: '',
  tshlGrade: '',
  tshlUnit: '',
  tshlStat: '',
  time: [],
})
const popOptions = { // 日期弹窗位置
  modifiers: [
    {
      name: 'flip',
      options: {
        fallbackPlacements: ['bottom'],
        allowedAutoPlacements: ['bottom'],
      }
    }
  ]
}
const earlyLoading = ref(false)
const earlyTrendLoading = ref(false)
//统计查询参数
const statForm = ref({
  time: [],
  responsibleUnit: undefined,
  isState: undefined,
})
const unitId = ref('')
//模块名称
const spanText = ('数据统计')
const spanText3 = ('信息列表')
const spanText4 = ('隐患趋势图')
const spanText5 = ('隐患处理占比图')
const filterText = ref('')
watch(filterText, (val) => {
  treeRefs.value!.filter(val)
})
var earlyTimes = ['2017/06/24', '2017/06/25', '2017/06/26', '2017/06/27', '2017/06/28', '2017/06/29', '2017/06/30']
var earlyCounts = [820, 932, 901, 934, 1290, 1330, 1320]
// echarts图1
const getPicture1 = () => {
  var timePeriodFaultChartDom = document.getElementById('picture1');
  var timePeriodFaultChart = echarts.init(timePeriodFaultChartDom);
  var timePeriodFaultOption;
  timePeriodFaultOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      },
      formatter: function (params) {
        var relVal = params[0].name
        for (var i = 0, l = params.length; i < l; i++) {
          relVal += '<br/>' + params[i].marker + params[i].seriesName + ' : ' + params[i].value + '个'
        }
        return relVal
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: earlyTimes,
        axisTick: {
          alignWithLabel: true
        },
        axisLabel: {
          interval: 0,
          textStyle: {
            fontSize: 12
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '个'
      }
    ],
    series: [
      {
        name: '隐患数量',
        type: 'line',
        data: earlyCounts,
        areaStyle: {},
        itemStyle: {
          color: '#3A74F5' // 设置折线的颜色为红色（十六进制表示）
        }
      }
    ],
    dataZoom: [
      {
        // 设置滚动条的隐藏与显示
        show: true,
        // 设置滚动条类型
        type: "slider",
        // 设置背景颜色
        // backgroundColor: "rgb(19, 63, 100)",
        // 设置选中范围的填充颜色
        // fillerColor: "rgb(16, 171, 198)",
        // 设置边框颜色
        // borderColor: "rgb(19, 63, 100)",
        // 是否显示detail，即拖拽时候显示详细数值信息
        showDetail: false,
        // 数据窗口范围的起始数值
        startValue: 0,
        // 数据窗口范围的结束数值（一页显示多少条数据）
        endValue: 10,
        // empty：当前数据窗口外的数据，被设置为空。
        // 即不会影响其他轴的数据范围
        filterMode: "empty",
        // 设置滚动条宽度，相对于盒子宽度
        width: "50%",
        // 设置滚动条高度
        height: 8,
        // 设置滚动条显示位置
        left: "center",
        // 是否锁定选择区域（或叫做数据窗口）的大小
        zoomLoxk: true,
        // 控制手柄的尺寸
        handleSize: 0,
        // dataZoom-slider组件离容器下侧的距离
        bottom: 3,
      },
      {
        // 没有下面这块的话，只能拖动滚动条，
        // 鼠标滚轮在区域内不能控制外部滚动条
        type: "inside",
        // 滚轮是否触发缩放
        zoomOnMouseWheel: false,
        // 鼠标滚轮触发滚动
        moveOnMouseMove: true,
        moveOnMouseWheel: true,
      },
    ]
  };
  timePeriodFaultOption && timePeriodFaultChart.setOption(timePeriodFaultOption);
}
var pieData = [{
  name: '已处理',
  value: 789
}, {
  name: '处理中',
  value: 469
}, {
  name: '挂起中',
  value: 272
}]
var pieLegendText = ['已处理', '处理中', '挂起中']
var pieTotal = 0
// 圆环图各环节的颜色
var pieColor = []
// echarts图2
const getPicture2 = () => {
  // 基于准备好的容器(这里的容器是id为chart1的div)，初始化echarts实例
  var chart1 = echarts.init(document.getElementById("picture2"))

  // 指定图表的配置项和数据
  var option = {

    //背景色
    backgroundColor: {			// 背景颜色
      type: 'linear',
      x: 0,
      y: 0,
      x2: 0,
      y2: 1,
      colorStops: [{
        offset: 0, color: '#ffffff' // 0% 处的颜色
      }, {
        offset: 0.5, color: '#ffffff' 	// 50% 处的颜色
      }, {
        offset: 1, color: '#ffffff' // 100% 处的颜色
      }],
      globalCoord: false // 缺省为 false
    },
    // 图例
    legend: [{
      selectedMode: true,             // 图例选择的模式，控制是否可以通过点击图例改变系列的显示状态。默认开启图例选择，可以设成 false 关闭。
      bottom: '10%',
      right: 'right',
      textStyle: {
        // 文字的样式
        fontSize: 14, // 可控制每个legend项的间距
        color: "#828282",// 图例的公用文本样式。
        rich: {
          a: {
            color: "#333333",
            fontSize: 14,
          },
          b: {
            // 设置百分比这一列的样式
            color: "rgba(0, 0, 0, 0.427450980392157)",
            fontSize: 12,
          },
        },
      },
      orient: 'vertical',
      data: pieLegendText,
      icon: 'circle',
      formatter: function (name) {	// 添加
        let total = 0
        let target
        for (let i = 0; i < pieData.length; i++) {
          total += pieData[i].value
          if (pieData[i].name === name) {
            target = pieData[i].value
          }
        }
        return `{a|${name}} {b|${' | ' + ((target / total) * 100).toFixed(2)}%}`;
      }
    }],

    // 提示框
    tooltip: {
      show: true,                 // 是否显示提示框
      formatter: '{b} : {c} 个 </br> 占比{d}%'      // 提示框显示内容,此处{b}表示各数据项名称，此项配置为默认显示项，{c}表示数据项的值，默认不显示，({d}%)表示数据项项占比，默认不显示。
    },

    // graphic 是原生图形元素组件。可以支持的图形元素包括：image, text, circle, sector, ring, polygon, polyline, rect, line, bezierCurve, arc, group,
    graphic: {
      type: 'text',               // [ default: image ]用 setOption 首次设定图形元素时必须指定。image, text, circle, sector, ring, polygon, polyline, rect, line, bezierCurve, arc, group,
      top: 'center',              // 描述怎么根据父元素进行定位。top 和 bottom 只有一个可以生效。如果指定 top 或 bottom，则 shape 里的 y、cy 等定位属性不再生效。『父元素』是指：如果是顶层元素，父元素是 echarts 图表容器。如果是 group 的子元素，父元素就是 group 元素。
      left: 'center',             // 同上
      style: {
        text: '各服装销量对比',       // 文本块文字。可以使用 \n 来换行。[ default: '' ]
        fill: '#fff',           // 填充色。
        fontSize: 16,           // 字体大小
        fontWeight: 'bold'		// 文字字体的粗细，可选'normal'，'bold'，'bolder'，'lighter'
      }
    },

    // 系列列表
    series: [{
      name: '圆环图系列名称',         // 系列名称
      type: 'pie',                    // 系列类型
      center: ['50%', '50%'],           // 饼图的中心（圆心）坐标，数组的第一项是横坐标，第二项是纵坐标。[ default: ['50%', '50%'] ]
      radius: ['30%', '45%'],         // 饼图的半径，数组的第一项是内半径，第二项是外半径。[ default: [0, '75%'] ]
      hoverAnimation: true,           // 是否开启 hover 在扇区上的放大动画效果。[ default: true ]
      color: pieColor,                   // 圆环图的颜色
      label: {                        // 饼图图形上的文本标签，可用于说明图形的一些数据信息，比如值，名称等.
        normal: {
          show: true,             // 是否显示标签[ default: false ]
          position: 'outside',    // 标签的位置。'outside'饼图扇区外侧，通过视觉引导线连到相应的扇区。'inside','inner' 同 'inside',饼图扇区内部。'center'在饼图中心位置。
          formatter: '{c}'  // 标签内容
        }
      },
      labelLine: {                    // 标签的视觉引导线样式,在 label 位置 设置为'outside'的时候会显示视觉引导线。
        normal: {
          show: true,             // 是否显示视觉引导线。
          length: 15,             // 在 label 位置 设置为'outside'的时候会显示视觉引导线。
          length2: 10,            // 视觉引导项第二段的长度。
          lineStyle: {            // 视觉引导线的样式
            //color: '#000',
            //width: 1
          }
        }
      },
      data: pieData                      // 系列中的数据内容数组。
    },
    {
      type: 'pie',
      radius: '0%',
      center: ['50%', '51%'],
      label: {
        position: 'center',
        color: 'rgba(0, 0, 0, 0.996)',
        fontSize: 22
      },
      data: [{
        name: pieTotal + '',
        value: pieTotal
      }],
      silent: true
    }],
    title: {
      // 主标题样式
      textStyle: {
        color: 'rgba(0, 0, 0, 0.647)',
        fontSize: 14
      },
      x: 'center',
      y: 'center',
      text: '总隐患数量',
      left: '44%',
      top: '40%'
    }

  };

  // 使用刚指定的配置项和数据显示图表
  chart1.setOption(option)
}

// 请求用户的权限树
const { getters } = useStore()
// 拿到vuex里面用户的信息
const UserInfo = computed(() => getters['user/getUserInfo'])
//隐患等级
const classTypeArr = ref<any>([])
//状态
const statusTypeArr = ref<any>([])

/**
 * @Name: 组织架构树-start
 * @Author: cdfy2
 * @Date: 2023/16/13  16:19:11
 * @param:
 */
//获取树
interface Tree {
  [key: string]: any
}
const organizes = ref([])
//格式化树
// const organizes = computed(() => getters['user/getOrganTree'])
// const authOrganIds = computed(() => getters['user/getAuthOrganIds'])
const isManager = computed(() => getters['user/getIsManager'])
//树状态数据
const treeData = ref<Tree[]>([])
//参数名称更换
const defaultProps = {
  children: 'children',
  label: 'name',
  disabled: 'disabled',
}
//默认选中组织目录第一个
const treeRefs = ref<any>(null)
//当前点击节点事件
const nodeRowData = ref<any>({
  children: []
})

const ergodicTree = (datas: any) => {
  datas.forEach((item: any) => {
    if (item.children.length > 0) {
      item.name = item.organizationName
      item.disabled = true
      ergodicTree(item.children)
    } else {
      item.id = item.organizationId
      item.name = item.organizationName
      item.catalogueId = item.organizationId
      item.children = []
    }
  })
  return datas
}
//默认选中组织目录第一个
const currentNodeData = ref()
const currentNodeKey = ref('')
const getTopOne = (data: any, types: number) => {
  if (data.children && data.children.length > 0) {
    getTopOne(data.children[0], types)
    if (types == 2) {
      if (data.children[0].children.length > 0) {
        handleNodeClick(data.children[0].children[0])
      } else {
        handleNodeClick(data.children[0])
      }
    }
  } else {
    nextTick(() => {
      currentNodeKey.value = data.id
      currentNodeData.value = data

    })
    return
  }
}

// 对树进行格式化
function convertData(data) {
  const result = []

  function traverse(node) {
    const newNode = {
      id: node.data.organId,
      label: node.data.name,
      value: node.data.organId,
      children: []
    }

    if (node.children.length > 0) {
      node.children.forEach((child) => {
        newNode.children.push(traverse(child))
      })
    }

    return newNode
  }

  data.forEach((node) => {
    result.push(traverse(node))
  })

  const rootNode = {
    id: 'root',
    label: '全部',
    value: 'root',
    children: result
  }

  return [rootNode]
}

// 左侧组织架构节点事件
const handleNodeClick = (data: any) => {
  nodeRowData.value = data
  localStorage.setItem('handleNodeRowNode', JSON.stringify(data))
  getList()
}

/**
 * @Name: 初始化
 * @Author: cdfy2
 * @Date: 2023/16/13  16:25:55
 * @param:  enclosure_type
 */

const initPage = async () => {
  // earlyLoading.value = true
  // earlyTrendLoading.value = true
  Promise.all([
    //查询数据字典
    // getResource('tcdm_early_level'),
    getEarlyState()

  ]).then(([res1]) => {
    // if (res1?.code === '1') {
    // classTypeArr.value = res1.data.properties.meta
    // if (res2?.code === '1') {
    // console.log(res1);
    let leveldata = [
      { id: 1, value: "一般隐患" },
      { id: 2, value: "严重隐患" },
      { id: 3, value: "较大隐患" },
    ];
    classTypeArr.value = leveldata;
    statusTypeArr.value = res1
    // }
    loadUnit()
    getList()
    getEarlyTrend()
  })
}

const loadUnit = () => {
  unitList().then(res => {
    if (res) {
      organizes.value = res
      // getOrganNames()
    }

  }).catch(e => {

  })
}

/**
 * @Name: 表格分页
 * @Author: cdfy2
 * @Date: 2023/16/13  16:26:05
 * @param:
 */
// 获取列表信息
const tableData = ref([])
// 表格分页
const pager = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageCount: 0,
})

interface OrderItem {
  column?: string
  method?: string
}
const sortChange = (data: any) => {
  console.log(data)
  const method = data.order === 'ascending' ? 'asc' : 'desc'
  order.value[0].column = data.prop
  order.value[0].method = method
  getList()
}


// 切换每页条数
const sizeChange = (size: number) => {
  pager.currentPage = 1
  pager.pageSize = size
  getList()
}
//切换当前页
const currentChange = (value: any) => {
  pager.currentPage = value
  pager.pageSize = 10
  getList()
}
// const dealSearchDate=()=>{
//    for (let i = 0; i < earlyTypeArr.length; i++) {

//    }
// }
//获取分页参数方法
const getList = async () => {
  // let classify = null;
  // for (let i = 0; i < earlyTypeArr.length; i++) {
  //   if (earlyTypeArr[i].tsharId == retrievedForm.value.tshlClassify) {
  //     classify = earlyTypeArr[i].tsharClassify;
  //   }
  // }
  // let unit = null;
  // for (let i = 0; i < organizes.length; i++) {
  //   if (organizes[i].id == retrievedForm.value.tshlUnit) {
  //     unit = organizes[i].departName;
  //   }
  // }
  // earlyLoading.value = true
  //分页参数
  const params = {
    page: {
      page: pager.currentPage - 1,
      size: pager.pageSize,
    },
    tcdmSecureHazardList: {
      ...retrievedForm.value,
      valid: '1'
      // timeStart: retrievedForm.value.time && retrievedForm.value.time.length === 2 ?retrievedForm.value.time[0]: '',
      // timeEnd: retrievedForm.value.time && retrievedForm.value.time.length === 2 ?retrievedForm.value.time[1]: '',
      // order: order.value
    },
    myTime2: {
      startTime: retrievedForm.value.time && retrievedForm.value.time.length === 2 ? retrievedForm.value.time[0] : '',
      endTime: retrievedForm.value.time && retrievedForm.value.time.length === 2 ? retrievedForm.value.time[1] : '',
    }
  }

  // 返回分页查询的结果
  inventoryPageList(params).then(res => {
    // if (res?.code == '1') {
    // 信息列表数据
    // tableData.value = res.content
    for (let i = 0; i < res.content.length; i++) {
      if (res.content[i].tshlGrade == 1) {
        res.content[i].tshlGrade = '一般隐患';
      }
      if (res.content[i].tshlGrade == 2) {
        res.content[i].tshlGrade = '严重隐患'
      }
      if (res.content[i].tshlGrade == 3) {
        res.content[i].tshlGrade = '较大隐患'
      }
    }
    tableData.value = res.content
    pager.total = res.totalElements
    //   pager.pageCount = Math.ceil(pager.total / pager.pageSize) === 0 ? 1 : Math.ceil(pager.total / pager.pageSize)
    //   earlyLoading.value = false
    //   ElMessage.success('信息列表查询成功')
    // } else {
    //   ElMessage.error('信息列表查询失败')
    // }
  }).catch(e => {
    ElMessage.error('服务器错误,请联系管理员')
  })

}

// 获取统计数据
const getEarlyTrend = async () => {
  // earlyTrendLoading.value = true
  const condition = {
    // ...statForm.value,
    // timeStart: statForm.value.time && statForm.value.time.length === 2 ? statForm.value.time[0] : '',
    // timeEnd: statForm.value.time && statForm.value.time.length === 2 ? statForm.value.time[1] : '',
    // order: [{
    //   'column': 'create_time',
    //   'method': 'asc'
    // }]
    myTime2: {
      startTime: statForm.value.time && statForm.value.time.length === 2 ? statForm.value.time[0] : '',
      endTime: statForm.value.time && statForm.value.time.length === 2 ? statForm.value.time[1] : '',
    },
    tcdmSecureHazardList: {
      tshlUnit: statForm.value.responsibleUnit,
      tshlStat: statForm.value.isState
    }
  }
  // getPicture1()
  earlyTimes = []
  pieLegendText = []
  pieTotal = 0
  earlyCounts = []
  pieData = []

  inventoryTrend(condition).then(res => {
    if (res) {
      console.log(res);
      earlyTimes = res.times
      earlyCounts = res.counts
      let totalcount = 0;
      // pieTotal = res.data.total
      var legendTexts = []
      pieColor = []
      res.pieData.forEach((item) => {
        statusTypeArr.value.forEach((state) => {
          if (item.name == state.tshsStat) {
            item.name = state.tshsStat
            legendTexts.push(state.tshsStat)
            pieColor.push(getColor(state.tshsId))
          }
        })
        totalcount += item.value
      })
      pieTotal = totalcount;
      pieLegendText = legendTexts
      console.log(pieLegendText);

      pieData = res.pieData
      ElMessage.success('数据统计查询成功')
    } else {
      ElMessage.error('数据统计查询失败')
    }
    getPicture1()
    getPicture2()
    earlyTrendLoading.value = false
  }).catch(e => {
    // getPicture1()
    ElMessage.error('服务器错误,请联系管理员')
  })


}
//清空重置
const order = ref([{
  'column': 'create_time',
  'method': 'desc'
}] as OrderItem[])
const searchReset = (data: any) => {
  retrievedForm.value = {
    id: undefined,
    earlyId: undefined,
    earlyLevel: undefined,
    responsibleUnit: undefined,
    isState: undefined,
    time: []
  }
  order.value = [{
    'column': 'create_time',
    'method': 'desc'
  }]
  pager.currentPage = 1
  pager.pageSize = 10
  tableData.value = []
  getList()
}
const filterStatus = (status: any) => {
  console.log(status);
  let dictName = ''
  statusTypeArr.value.filter((item: any) => {
    if (status == item.tshsId) {
      dictName = item.tshsStat
    }
  })
  return dictName
}
const setLevelDesc = (status: any) => {
  let dictName = ''
  classTypeArr.value.filter((item: any) => {
    if (status == item.value) {
      dictName = item.label
    }
  })
  return dictName
}
const getColor = (status: any) => {
  let color = ''
  switch (status) {
    case 1:
      color = '#8D65F1'
      break
    case 2:
      color = '#2F7DF1'
      break
    case 3:
      color = '#33B0E9'
      break
    case 4:
      color = '#88CF4B'
      break
    case 5:
      color = '#F7C652'
      break
    // case '5':
    //   color = '#FF8F3A'
    //   break
  }
  return color
}
const getBackColor = (status: any) => {
  let color = ''
  switch (status) {
    case '0':
      color = '#EE6666'
      break
    case '1':
      color = '#9FE080'
      break
    case '2':
      color = '#72DEB2'
      break
    case '3':
      color = '#40B27D'
      break
    case '4':
      color = '#73A0FA'
      break
    case '5':
      color = '#7384A1'
      break
  }
  return color
}
//跳转接口
const addRouter = (data: any, row: any) => {
  if (data === 1) {
    router.push({
      path: '/secure/defect/inventory/add',
      query: {
        nodeRowData: row.tshlId,
      }
    })
  }
}

const filterUnitNode = (value, data) => data.organizationName.includes(value)
var oranNames = {}
var getOrganNames = () => {
  oranNames = {}
  organizes.value.forEach(item => {
    oranNames[item.id + ''] = item.unitName
  })
}

const setUnitName = (id) => {
  return oranNames[id + '']
}

const resetStatForm = () => {
  statForm.value = {
    time: [],
    responsibleUnit: undefined,
    isState: undefined,
  }
  getEarlyTrend()
}
const earlyTypeArr = ref([])
/**
 * 获取隐患类型列表
 */
const getEarlyTypeList = () => {
  earlyTypeList({}).then(res => {
    earlyTypeArr.value = []
    // if (res && res.data) {
    let typeArr = [];
    typeArr[0] = res[0];
    let count = 1;
    for (let i = 1; i < res.length; i++) {
      for (let j = 0; j < typeArr.length; j++) {
        if (typeArr[j].tsharClassify == res[i].tsharClassify) {
          break;
        }
      }
      if (j >= typeArr.length) {
        typeArr[count++] = res[i]
      }
    }
    earlyTypeArr.value = typeArr
    // }
  }).catch(e => { })
}

// 1查看 2编辑
let handelType = ref({ text: "查看", code: 'review' })
// 编辑
const editVisible = ref(false)
// 查看,编辑数据
let list = ref()

//弹框点击消失
const cancel = () => {
  editVisible.value = false
  // 重新查询
  getEarlyTypeList()
  initPage()
}

const handleEarly =async(row, isEdit) => {
  editVisible.value = true
  // list.value = row
  let data={
    row:row,
    pictureFile:null,
    accessory:null
  }
  const pictureParam = {
      tshlId: row.tshlId,
      fileLocation: 1
    }
    const accessoryParam={
      tshlId:  row.tshlId,
      fileLocation: 2      
    }
    const pic = await findFile(pictureParam)
    const acc= await findFile(accessoryParam)
    const pictureFile = pic.map((item: any) => {
      return {
        fileId: item.fileId,
        fileName: item.fileName,
        fileSize: item.fileSize,
        filePath: item.filePath,
        fileType: item.fileType,
        fileLocation: item.fileLocation,
        tshlId: item.tshlId
      }
    }) || []
    
    const accessory = acc.map((item: any) => {
      return {
        fileId: item.fileId,
        fileName: item.fileName,
        fileSize: item.fileSize,
        filePath: item.filePath,
        fileType: item.fileType,
        fileLocation: item.fileLocation,
        tshlId: item.tshlId
      }
    }) || []
  data.pictureFile=pictureFile;
  data.accessory=accessory;
  list.value = data
  list.value.isStateDesc = filterStatus(row.isState)
  list.value.earlyLevelDesc = setLevelDesc(row.earlyLevel)
  list.value.responsibleUnitDesc = setUnitName(row.responsibleUnit)
  list.value.problemSourcesDesc = setUnitName(row.problemSources)
  if (row.tshlStat == '0') {
    handelType.value = { text: "处理", code: 'back', isEdit: isEdit }
  }
  if (row.tshlStat == '1' || row.tshlStat == '4') {
    handelType.value = { text: "查看", code: 'review', isEdit: isEdit }
  }
  else if (row.tshlStat == '2') {
    handelType.value = { text: "处理", code: 'handle', isEdit: isEdit }
  } else if (row.tshlStat == '3') {
    handelType.value = { text: "验收", code: 'accept', isEdit: isEdit }
  } else if (row.tshlStat == '5') {
    handelType.value = { text: "解除", code: 'free', isEdit: isEdit }
  }

}
const deleteEarly = (row) => {
  deleteInventory({ tshlId: row.tshlId }).then(res => {
    // if (res.code == 1) {
    getList()
    //   ElMessage.success('删除成功')
    // }
  }).catch(e => { })
}
/**
 * @Name: 页面挂在后执行
 * @Author: cdfy2
 * @Date: 2023/16/13  16:27:29
 */
onMounted(() => {
  let forward: any = router.options.history.state.forward
  if (forward == null) {
    localStorage.removeItem('handleNodeRowNode')
  }
  getEarlyTypeList()
  initPage()
})
</script>

<style scoped lang="less">
@import url("../style/publicStyle.less");

.container {
  .tableColumns {
    .table-stat {
      height: 500px;
    }

    .table-select {
      height: 70px;
    }
  }
}

.statusRow {
  width: 100px;
  padding: 2px 5px;
  margin: 0 auto;
  border: 1px solid #ebeef5;
  background: #0e595e;
  color: #ebeef5;
  border-radius: 5px;
}

.el-select {
  width: 280px !important;
}

.el-input {
  width: 280px !important;
}

.link-btn {
  color: #2F7DF1;
}

.link-btns {
  color: #F24A45;
}

.el-form-item {
  width: 410px !important;
}
</style>
